package com.glory.wxelectricitypda.activity;

import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glory.wxelectricitypda.R;
import com.glory.wxelectricitypda.base.BaseDialogActivity;
import com.glory.wxelectricitypda.bean.BoxLabelReviewBean;
import com.glory.wxelectricitypda.bean.LotBean;
import com.glory.wxelectricitypda.bean.ResponseBean;
import com.glory.wxelectricitypda.fragment.PDAPackingFragment;
import com.glory.wxelectricitypda.fragment.PackagedFragment;
import com.glory.wxelectricitypda.fragment.UnPDAPackingFragment;
import com.glory.wxelectricitypda.fragment.UnpackagedFragment;
import com.glory.wxelectricitypda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_TabEntity;
import com.pda.platform.ui.ui_pdaplatform.tablayout.CommonTabLayout;
import com.pda.platform.ui.ui_pdaplatform.tablayout.listener.CustomTabEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

import butterknife.BindView;

public class PDAPackingActivity extends BaseDialogActivity {

    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tabLayout)
    CommonTabLayout tabLayout;
    @BindView(R.id.flPrinter)
    FrameLayout flPrinter;
    @BindView(R.id.tvPrinter)
    TextView tvPrinter;
    @BindView(R.id.boxNum)
    FreeUI_ClearEditText boxNum;
    @BindView(R.id.etUser)
    FreeUI_ClearEditText etUser;
    @BindView(R.id.ivPrinter)
    ImageView ivPrinter;

    private PDAPackingFragment pDAPackingFragment;
    private UnPDAPackingFragment unPDAPackingFragment;
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private ArrayList<String> printerList = new ArrayList<>();
    private Map<String, String> printerKeyMap = new HashMap<>();
    private Map<String, String> printerTextMap = new HashMap<>();
    private FreeUI_GeneralPop mPrinterPop;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pdapacking;
    }


    @Override
    protected void initView() {
        super.initView();

        freeUI_titleView.setTitle("PDA装箱");
        freeUI_titleView.setRightListener("装箱", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (etUser.getText().toString().isEmpty()){
                    showToast("请输入工号！",false);
                    return;
                }
                if (tvPrinter.getText().toString().isEmpty()){
                    showToast("请选择打印机！",false);
                    return;
                }
                if (pDAPackingFragment.mUnpackagedAdapter.getData().size()<=0){
                    showToast("暂无盒号数据！",false);
                    return;
                }
                submit();
            }
        });

        pDAPackingFragment = new PDAPackingFragment();
        mFragments.add(pDAPackingFragment);
        unPDAPackingFragment = new UnPDAPackingFragment();
        mFragments.add(unPDAPackingFragment);
        mTabEntities.add(new FreeUI_TabEntity("已审核盒号",
                null, null));
        mTabEntities.add(new FreeUI_TabEntity("已审核箱号",
                null, null));
        tabLayout.setTabData(mTabEntities, this, R.id.content, mFragments);

    }

    @Override
    protected void initData() {
        super.initData();

        reasonsForNoReturn();

        initEdit(boxNum,s->{
            queryBoxLabelReview();
        });

        flPrinter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mPrinterPop != null) {
                    if (mPrinterPop.isShowing()) {
                        mPrinterPop.dismiss();
                    }
                } else {
                    mPrinterPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flPrinter.getWidth(), printerList, ivPrinter, new FreeUI_TextCallback() {
                        @Override
                        public void onSuccess(String s) {
                            tvPrinter.setText(s);
                        }
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivPrinter);
                mPrinterPop.showAsDropDown(flPrinter, 0, 0);

            }
        });
    }


    private void submit(){

        JSONObject map = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        try {
            map.put("ACTIONTYPE", "GENERATE");
            map.put("PRINTER", printerTextMap.get(tvPrinter.getText().toString()));
            map.put("IP", printerKeyMap.get(tvPrinter.getText().toString()));
            map.put("XPACKAGEDETAILS", new JSONArray(new Gson().toJson(pDAPackingFragment.mUnpackagedAdapter.getData())));
            jsonObject.put("Data", map);
            jsonObject.put("MessageName", "EUIT.PRINTBOX");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<BoxLabelReviewBean>>(
                new TypeToken<ResponseBean<BoxLabelReviewBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onSuccess(Response<ResponseBean<BoxLabelReviewBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    showToast("提交成功！",true);
                    pDAPackingFragment.mUnpackagedAdapter.setNewData(null);
                    response.body().getBody().getXPACKAGEDETAILS().forEach(new Consumer<BoxLabelReviewBean.XPACKAGEDETAILDTO>() {
                        @Override
                        public void accept(BoxLabelReviewBean.XPACKAGEDETAILDTO xpackagedetaildto) {

                            unPDAPackingFragment.addData(xpackagedetaildto.getPACKLOTID());
                        }
                    });

                }
            }

            @Override
            public void onError(Response<ResponseBean<BoxLabelReviewBean>> response) {
                super.onError(response);
                loadError(response.getException(), "LABELCHECK");
            }
        });



    }

    private void queryBoxLabelReview() {

        if (etUser.getText().toString().isEmpty()){
            showToast("请输入工号！",false);
            return;
        }

        JSONObject map = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        try {
            map.put("PACKLOTID", boxNum.getText().toString());
            map.put("XPACKAGEDETAILS", new JSONArray(new Gson().toJson(pDAPackingFragment.mUnpackagedAdapter.getData())));
            jsonObject.put("Data", map);
            jsonObject.put("MessageName", "EUIT.PRINTBOX");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<BoxLabelReviewBean>>(
                new TypeToken<ResponseBean<BoxLabelReviewBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<BoxLabelReviewBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {


//                    pDAPackingFragment.addData(response.body().getBody().getXPACKAGEDETAILS().get(0));
                    pDAPackingFragment.mUnpackagedAdapter.setNewData(response.body().getBody().getXPACKAGEDETAILS());
                    pDAPackingFragment.mUnpackagedAdapter.notifyDataSetChanged();
                    boxNum.setText("");
                }
            }

            @Override
            public void onError(Response<ResponseBean<BoxLabelReviewBean>> response) {
                super.onError(response);
                loadError(response.getException(), "LABELCHECK");
            }
        });


    }


    private void reasonsForNoReturn(){

        JSONObject map = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        try {
            map.put("ACTIONTYPE", "GETBYREFNAME");
            map.put("REFNAME", "EUIT_PACKAGE_PRINTER");
            jsonObject.put("Data", map);
            jsonObject.put("MessageName", "EUIT.EuitADUREFLISTHANDLER");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                new TypeToken<ResponseBean<LotBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LotBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    for (LotBean.AdurefBean adurefBean : response.body().getBody().getADUREFLIST()) {
                        printerList.add(adurefBean.getDESCRIPTION());
                        printerKeyMap.put(adurefBean.getDESCRIPTION(), adurefBean.getKEYID());
                        printerTextMap.put(adurefBean.getDESCRIPTION(), adurefBean.getTEXT());
                    }

                }
            }

            @Override
            public void onError(Response<ResponseBean<LotBean>> response) {
                super.onError(response);
                loadError(response.getException(), "ADUREFLISTHANDLER");
            }
        });

    }


    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return new FreeUI_AddViewEntity("header", llMain);
    }
}